package pi.server.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Vector;

import pi.server.core.MyProgram;

public class ServerNetwork extends Thread{
	private ServerSocket serverSocket;
	private int maxClients;
	public Vector<ClientNetwork> clientList;
	public int clientsIds;
	
	protected MyProgram program;
	
	private Thread showDataTimerThread;

	public ServerNetwork(int port, MyProgram program){
		try{
			port=34523;
			serverSocket = new ServerSocket(port);
			maxClients = 2;
			clientList = new Vector<ClientNetwork>();
			clientsIds = 0;
			
			this.program = program;
			program.serverGUI.SetText("Server Nerwork created on port " + port + "!" + "\n");
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	@Override public void run(){
		showDataTimerThread = new Thread(new Runnable(){
			@SuppressWarnings("static-access")
			@Override public void run(){
				while(program.serverConnected){
//					ShowClients();
					try{
						showDataTimerThread.sleep(10000);
					}catch(InterruptedException e){
						e.printStackTrace();
					}
				}
			}
		});		
		showDataTimerThread.start();
		
		while(program.serverConnected){
			WaitNewClient();
		}
	}
	
	private void WaitNewClient(){
		try{
			clientsIds++;
			ClientNetwork incomingClient = null;

			if(clientList.size() < maxClients){
				incomingClient = new ClientNetwork(this, serverSocket.accept(), true);
				incomingClient.start();
				incomingClient.SendServerSizeToAllClients();
//			}else{
//				incomingClient = new ClientNetwork(this, serverSocket.accept(), false);
//				incomingClient.KickedByServer();
//				program.serverGUI.SetText("new client try connect!");
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}

	public void RemoveClientAndRefreshClientList(ClientNetwork client){
		if(clientList.size() > 0){
			for(int i = 0; i < clientList.size(); i++){
				if(clientList.get(i) == client && clientList.get(i).player.isConnected == false){
					clientList.remove(i);		
					client.SendServerSizeToAllClients();
				}
			}
		}
	}
	
//	private void ShowClients(){
//		if(clientList.size() > 0){
//			for(int i = 0; i < clientList.size(); i++){
//				clientList.get(i).ShowData();
//			}
//			System.out.println();
//		}else{
//			System.out.println("no clients online!");
//		}
//	}
}